﻿using Microsoft.Extensions.Options;
using SBlogCore.Common.App.Options;
using SBlogCore.Common.FileUploadExtend.Attributes;
using System.Reflection;

namespace SBlogCore.Common.FileUploadExtend
{
    public class FileUploadFactory
    {
        private readonly Dictionary<string, FileUploadStrategyAbstract> _handlers = new();

        public FileUploadFactory(IOptions<AppsettingsOptions> options)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var types = assembly.GetTypes().Where(w => w.IsAssignableTo(typeof(FileUploadStrategyAbstract))&&w.IsDefined(typeof(FileTypeAttribute),false));
            foreach (var type in types)
            {
                if (Activator.CreateInstance(type) is not FileUploadStrategyAbstract fileUpload) continue;
                var attribute = type.GetCustomAttribute<FileTypeAttribute>()!;
                var uploadFileOptions = options.Value.UploadFile;
                var fileOptions = uploadFileOptions?.Options.FirstOrDefault(w => w.FileType == attribute.Name);
                if (fileOptions != null) fileUpload.LoadOption(fileOptions, uploadFileOptions?.UploadFilePath??"wwwroot");
                _handlers.Add(attribute.Name, fileUpload);
            }
        }
        /// <summary>
        /// 获取实例
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public  FileUploadStrategyAbstract GetInstance(string? key=null)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                key = "any";
            }
            var lowerKey = key.ToLower();
            if (_handlers.ContainsKey(lowerKey))
            {
                return _handlers[lowerKey];
            }
            throw new Exception("Key不存在");
        }
    }
}
